﻿using Quartz.Impl;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HsServerHa.Core;
using System.Collections.Specialized;

namespace HsServerHa.Common
{
    public class QuartzHelperNew
    { 

        public static async void Start() {
            NameValueCollection props = new NameValueCollection
          {
              { "quartz.serializer.type", "binary" }
            };
            //实例化调度工厂
            StdSchedulerFactory factory = new StdSchedulerFactory(props);

            //生成调度器
            scheduler = await factory.GetScheduler();
            await scheduler.Start();
        }
        private static IScheduler scheduler;
        /// <summary>
        /// 定时执行任务
        /// </summary>
        /// <typeparam name="T">任务类，必须实现IJob接口</typeparam>
        /// <param name="jobinfo">任务信息</param>
        public static async Task ExecuteByCron<T>(TaskInfo jobinfo, Dictionary<string, object> dic = null) where T : IJob
        {
            if (scheduler == null)
            {
                Start();
            }
            IJobDetail job = JobBuilder.Create<T>()
             .WithIdentity(jobinfo.TaskName, jobinfo.GroupName)//指定工作名称和分组名称创建job
             .Build();
            if (dic != null)
            {
                foreach (var item in dic)
                {
                    job.JobDataMap.Put(item.Key, item.Value);
                }
            }
            var trigger = TriggerBuilder.Create()
                                     .WithIdentity(jobinfo.id.ToString(), jobinfo.GroupName)//指定触发器名称和分组名称创建触发器
            .WithCronSchedule(jobinfo.CronStr)//cron表达式指定执行时间
                                     .Build();
            await scheduler.ScheduleJob(job, trigger);// 将job和触发器加入调度器
        }
        /// <summary>
        /// 时间间隔执行任务
        /// </summary>
        /// <typeparam name="T">任务类，必须实现IJob接口</typeparam>
        /// <param name="seconds">时间间隔(单位：秒)</param>
        public static async Task ExecuteInterval<T>(int seconds, Dictionary<string, object> dic = null) where T : IJob
        {
            if (scheduler == null)
            {
                Start();
            }
            IJobDetail job = JobBuilder.Create<T>().Build();
            if (dic != null)
            {
                foreach (var item in dic)
                {
                    job.JobDataMap.Put(item.Key, item.Value);
                }
            }
            ITrigger trigger = TriggerBuilder.Create().StartNow().WithSimpleSchedule(x => x.WithIntervalInSeconds(seconds).RepeatForever()).Build();
            await scheduler.ScheduleJob(job, trigger);
        }
    }
}
